import { useState, useEffect } from 'react'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Badge } from '@/components/ui/badge'
import { Progress } from '@/components/ui/progress'
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import { Textarea } from '@/components/ui/textarea'
import { 
  Play, 
  Pause, 
  Square, 
  TrendingUp,
  Brain,
  BarChart3,
  FileText,
  Clock,
  CheckCircle,
  AlertCircle,
  Settings,
  X,
  Download,
  Table,
  Eye
} from 'lucide-react'
import { toast } from 'sonner'
import apiService from '../services/api'
import DemoModeAlert from './DemoModeAlert'

export default function PredictionAnalysis() {
  const [activeTab, setActiveTab] = useState('create')
  const [tasks, setTasks] = useState([])
  const [companies, setCompanies] = useState([])
  const [products, setProducts] = useState([])
  const [loading, setLoading] = useState(false)
  const [creating, setCreating] = useState(false)
  const [selectedTask, setSelectedTask] = useState(null)
  const [predictionData, setPredictionData] = useState(null)
  const [showPredictionModal, setShowPredictionModal] = useState(false)
  const [showDemoAlert, setShowDemoAlert] = useState(false)
  
  // 创建任务表单
  const [taskForm, setTaskForm] = useState({
    task_name: '',
    task_type: 'group_prediction',
    company_ids: [],
    product_ids: [],
    prediction_years: '2025',
    description: '',
    strategic_growth_rates: {
      human_drug_formulation: 0,
      human_drug_raw_material: 0,
      plant_protection: 0,
      animal_protection: 0
    }
  })

  // 任务状态轮询
  const [pollingTasks, setPollingTasks] = useState(new Set())

  useEffect(() => {
    loadTasks()
    loadCompanies()
  }, [])

  useEffect(() => {
    // 设置轮询检查运行中的任务
    const interval = setInterval(() => {
      pollingTasks.forEach(taskId => {
        checkTaskStatus(taskId)
      })
    }, 3000)

    return () => clearInterval(interval)
  }, [pollingTasks])

  const loadTasks = async () => {
    try {
      setLoading(true)
      const response = await apiService.getPredictionTasks({ page: 1, page_size: 50 })
      const items = response.data?.items || []
      
      setTasks(items)
      
      // 添加运行中的任务到轮询列表
      const runningTasks = items.filter(task => task.status === 'running').map(task => task.task_id)
      setPollingTasks(new Set(runningTasks))
    } catch (error) {
      console.error('加载任务列表失败:', error)
      // 使用模拟数据作为后备
      setTasks([
        {
          task_id: '1',
          task_name: '2026年医药产品预测',
          status: 'completed',
          progress: 100,
          created_at: '2024-08-26T10:00:00Z',
          task_type: 'multi_product'
        },
        {
          task_id: '2',
          task_name: '重点产品销售预测',
          status: 'running',
          progress: 75,
          created_at: '2024-08-26T11:00:00Z',
          task_type: 'single_product'
        }
      ])
    } finally {
      setLoading(false)
    }
  }

  const loadCompanies = async () => {
    try {
      const response = await apiService.getCompanies()
      setCompanies(response.data || [])
    } catch (error) {
      console.error('加载公司列表失败:', error)
      // 使用子公司数据作为后备
      setCompanies([
        { id: 'head_office', name: '总厂' },
        { id: 'biology', name: '生物' },
        { id: 'hainan', name: '海南' },
        { id: 'huanghe', name: '黄河' },
        { id: 'anti', name: '安替' },
        { id: 'anxin', name: '安信' },
        { id: 'anhong', name: '安弘' },
        { id: 'anshun', name: '安舜' },
        { id: 'inner_mongolia_total', name: '内蒙合计' },
        { id: 'hohhot', name: '呼和浩特' },
        { id: 'hulunbeier', name: '呼伦贝尔' },
        { id: 'huaxing', name: '华星' },
        { id: 'qifa', name: '齐发' },
        { id: 'animal_health', name: '动保' },
        { id: 'shenghua', name: '晟华' },
        { id: 'wanze', name: '万泽' },
        { id: 'import_export', name: '进出口公司' },
        { id: 'human_drug_foreign_trade', name: '人药制剂事业部外贸部' },
        { id: 'animal_health_foreign_trade', name: '动保外贸' }
      ])
    }
  }

  const loadProducts = async (companyId) => {
    try {
      const response = await apiService.getProducts(companyId)
      setProducts(response.data || [])
    } catch (error) {
      console.error('加载产品列表失败:', error)
    }
  }

  const checkTaskStatus = async (taskId) => {
    try {
      const response = await apiService.getTaskStatus(taskId)
      const taskStatus = response.data
      
      setTasks(prev => prev.map(task => 
        task.task_id === taskId 
          ? { ...task, status: taskStatus.status, progress: taskStatus.progress }
          : task
      ))

      // 如果任务完成，从轮询列表中移除
      if (taskStatus.status === 'completed' || taskStatus.status === 'failed') {
        setPollingTasks(prev => {
          const newSet = new Set(prev)
          newSet.delete(taskId)
          return newSet
        })
        
        if (taskStatus.status === 'completed') {
          toast.success(`任务 "${taskStatus.task_name || taskId}" 已完成`)
        } else {
          toast.error(`任务 "${taskStatus.task_name || taskId}" 执行失败`)
        }
      }
    } catch (error) {
      console.error('检查任务状态失败:', error)
    }
  }

  // 将年份范围转换为年份数组
  const parseYearRange = (yearRange) => {
    if (yearRange.includes('-')) {
      const [startYear, endYear] = yearRange.split('-').map(y => parseInt(y))
      const years = []
      for (let year = startYear; year <= endYear; year++) {
        years.push(year)
      }
      return years
    } else {
      return [parseInt(yearRange)]
    }
  }

  const handleCreateTask = async () => {
    try {
      setCreating(true)
      
      // 验证表单
      if (!taskForm.task_name.trim()) {
        toast.error('请输入任务名称')
        return
      }
      
      if (taskForm.task_type !== 'group_prediction' && taskForm.company_ids.length === 0) {
        toast.error('请选择至少一个公司')
        return
      }

      // 转换预测年份
      const predictionYears = parseYearRange(taskForm.prediction_years)

      const response = await apiService.createPredictionTask({
        ...taskForm,
        prediction_years: predictionYears,  // 使用转换后的年份数组
        created_by: 'user001'
      })
      
      const newTask = response.data
      toast.success('预测任务创建成功')
      
      // 添加到任务列表
      setTasks(prev => [newTask, ...prev])
      
      // 添加到轮询列表
      setPollingTasks(prev => new Set([...prev, newTask.task_id]))
      
                    // 重置表单
              setTaskForm({
                task_name: '',
                task_type: 'group_prediction',
                company_ids: [],
                product_ids: [],
                prediction_years: '2025',
                description: '',
                strategic_growth_rates: {
                  human_drug_formulation: 0,
                  human_drug_raw_material: 0,
                  plant_protection: 0,
                  animal_protection: 0
                }
              })
      
      // 切换到任务列表
      setActiveTab('tasks')
    } catch (error) {
      console.error('创建任务失败:', error)
      toast.error(error.message || '创建任务失败')
    } finally {
      setCreating(false)
    }
  }

  const handleDeleteTask = async (taskId) => {
    try {
      await apiService.deleteTask(taskId)
      setTasks(prev => prev.filter(task => task.task_id !== taskId))
      setPollingTasks(prev => {
        const newSet = new Set(prev)
        newSet.delete(taskId)
        return newSet
      })
      toast.success('任务已删除')
    } catch (error) {
      console.error('删除任务失败:', error)
      toast.error('删除任务失败')
    }
  }

  const handleViewPrediction = async (task) => {
    try {
      setLoading(true)
      const response = await apiService.getTaskResults(task.task_id)
      setSelectedTask(task)
      setPredictionData(response.data)
      setShowPredictionModal(true)
    } catch (error) {
      console.error('获取预测结果失败:', error)
      toast.error('获取预测结果失败')
    } finally {
      setLoading(false)
    }
  }

  const getStatusIcon = (status) => {
    switch (status) {
      case 'completed':
        return <CheckCircle className="h-4 w-4 text-green-500" />
      case 'running':
        return <Clock className="h-4 w-4 text-blue-500" />
      case 'failed':
        return <AlertCircle className="h-4 w-4 text-red-500" />
      case 'pending':
        return <Clock className="h-4 w-4 text-yellow-500" />
      default:
        return <Clock className="h-4 w-4 text-gray-500" />
    }
  }

  const getStatusBadge = (status) => {
    const variants = {
      completed: 'default',
      running: 'secondary',
      failed: 'destructive',
      pending: 'outline'
    }
    const labels = {
      completed: '已完成',
      running: '进行中',
      failed: '失败',
      pending: '待开始'
    }
    return <Badge variant={variants[status]}>{labels[status]}</Badge>
  }

  const formatDate = (dateString) => {
    if (!dateString) return '-'
    return new Date(dateString).toLocaleString('zh-CN')
  }

  return (
    <div className="p-6 space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-3xl font-bold text-gray-900">预测分析</h1>
          <p className="text-gray-600 mt-1">创建和管理AI预测分析任务</p>
        </div>
        <div className="flex space-x-3">
          <Button variant="outline" onClick={() => setShowDemoAlert(true)}>
            <Play className="h-4 w-4 mr-2" />
            新建预测
          </Button>
          <Button onClick={() => setActiveTab('tasks')}>
            <BarChart3 className="h-4 w-4 mr-2" />
            任务列表
          </Button>
        </div>
      </div>

      {/* Tabs */}
      <Tabs value={activeTab} onValueChange={setActiveTab} className="space-y-6">
        <TabsList className="grid w-full grid-cols-3 bg-gray-100 p-1 rounded-lg">
          <TabsTrigger 
            value="create" 
            onClick={(e) => { e.preventDefault(); setShowDemoAlert(true); }}
            className="flex items-center justify-center px-4 py-3 text-sm font-medium transition-all duration-200 rounded-md hover:bg-white hover:shadow-sm data-[state=active]:bg-white data-[state=active]:shadow-sm data-[state=active]:text-blue-600"
          >
            <Settings className="h-4 w-4 mr-2" />
            创建任务
          </TabsTrigger>
          <TabsTrigger 
            value="tasks"
            className="flex items-center justify-center px-4 py-3 text-sm font-medium transition-all duration-200 rounded-md hover:bg-white hover:shadow-sm data-[state=active]:bg-white data-[state=active]:shadow-sm data-[state=active]:text-blue-600"
          >
            <BarChart3 className="h-4 w-4 mr-2" />
            任务管理
          </TabsTrigger>
          <TabsTrigger 
            value="results"
            className="flex items-center justify-center px-4 py-3 text-sm font-medium transition-all duration-200 rounded-md hover:bg-white hover:shadow-sm data-[state=active]:bg-white data-[state=active]:shadow-sm data-[state=active]:text-blue-600"
          >
            <FileText className="h-4 w-4 mr-2" />
            预测结果
          </TabsTrigger>
        </TabsList>

        {/* Create Task Tab */}
        <TabsContent value="create">
          <Card>
            <CardHeader>
              <CardTitle>创建预测任务</CardTitle>
              <CardDescription>
                配置预测参数，启动AI智能预测分析
              </CardDescription>
            </CardHeader>
            <CardContent className="space-y-6">
              {/* Basic Info */}
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div className="space-y-2">
                  <Label htmlFor="task-name">任务名称</Label>
                  <Input
                    id="task-name"
                    placeholder="输入任务名称"
                    value={taskForm.task_name}
                    onChange={(e) => setTaskForm(prev => ({ ...prev, task_name: e.target.value }))}
                  />
                </div>
                <div className="space-y-2">
                  <Label htmlFor="task-type">任务类型</Label>
                  <Select 
                    value={taskForm.task_type} 
                    onValueChange={(value) => setTaskForm(prev => ({ ...prev, task_type: value }))}
                  >
                    <SelectTrigger>
                      <SelectValue placeholder="选择任务类型" />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="group_prediction">集团预测</SelectItem>
                      <SelectItem value="multi_product">多产品预测</SelectItem>
                      <SelectItem value="single_product">单产品预测</SelectItem>
                      <SelectItem value="subsidiary_prediction">子公司预测</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
              </div>

              {/* Company Selection - 只在非集团预测时显示 */}
              {taskForm.task_type !== 'group_prediction' && (
                <div className="space-y-2">
                  <Label>选择公司</Label>
                  <div className="grid grid-cols-2 md:grid-cols-3 gap-2">
                    {companies.map((company) => (
                      <label key={company.id} className="flex items-center space-x-2 p-2 border rounded cursor-pointer hover:bg-gray-50">
                        <input
                          type="checkbox"
                          checked={taskForm.company_ids.includes(company.id)}
                          onChange={(e) => {
                            if (e.target.checked) {
                              setTaskForm(prev => ({
                                ...prev,
                                company_ids: [...prev.company_ids, company.id]
                              }))
                            } else {
                              setTaskForm(prev => ({
                                ...prev,
                                company_ids: prev.company_ids.filter(id => id !== company.id)
                              }))
                            }
                          }}
                        />
                        <span className="text-sm">{company.name}</span>
                      </label>
                    ))}
                    {companies.length === 0 && (
                      <div className="col-span-full text-center py-4 text-gray-500">
                        暂无公司数据
                      </div>
                    )}
                  </div>
                </div>
              )}

              {/* Prediction Years */}
              <div className="space-y-2">
                <Label>预测年份</Label>
                <Select 
                  value={taskForm.prediction_years} 
                  onValueChange={(value) => setTaskForm(prev => ({ ...prev, prediction_years: value }))}
                >
                  <SelectTrigger>
                    <SelectValue placeholder="选择预测年份范围" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="2025">2025年</SelectItem>
                    <SelectItem value="2025-2026">2025-2026年</SelectItem>
                    <SelectItem value="2025-2027">2025-2027年</SelectItem>
                    <SelectItem value="2025-2028">2025-2028年</SelectItem>
                    <SelectItem value="2025-2029">2025-2029年</SelectItem>
                    <SelectItem value="2025-2030">2025-2030年</SelectItem>
                  </SelectContent>
                </Select>
              </div>

              {/* Strategic Growth Rates - 只在集团预测时显示 */}
              {taskForm.task_type === 'group_prediction' && (
                <div className="space-y-4">
                  <Label>集团战略增速配置 (%)</Label>
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div className="space-y-2">
                      <Label htmlFor="human-drug-formulation">人药制剂板块</Label>
                      <Input
                        id="human-drug-formulation"
                        type="number"
                        step="0.01"
                        placeholder="请输入增速（%）"
                        value={taskForm.strategic_growth_rates.human_drug_formulation}
                        onChange={(e) => setTaskForm(prev => ({
                          ...prev,
                          strategic_growth_rates: {
                            ...prev.strategic_growth_rates,
                            human_drug_formulation: parseFloat(e.target.value) || 0
                          }
                        }))}
                      />
                    </div>
                    <div className="space-y-2">
                      <Label htmlFor="human-drug-raw">人药原料板块</Label>
                      <Input
                        id="human-drug-raw"
                        type="number"
                        step="0.01"
                        placeholder="请输入增速（%）"
                        value={taskForm.strategic_growth_rates.human_drug_raw_material}
                        onChange={(e) => setTaskForm(prev => ({
                          ...prev,
                          strategic_growth_rates: {
                            ...prev.strategic_growth_rates,
                            human_drug_raw_material: parseFloat(e.target.value) || 0
                          }
                        }))}
                      />
                    </div>
                    <div className="space-y-2">
                      <Label htmlFor="plant-protection">植保板块</Label>
                      <Input
                        id="plant-protection"
                        type="number"
                        step="0.01"
                        placeholder="请输入增速（%）"
                        value={taskForm.strategic_growth_rates.plant_protection}
                        onChange={(e) => setTaskForm(prev => ({
                          ...prev,
                          strategic_growth_rates: {
                            ...prev.strategic_growth_rates,
                            plant_protection: parseFloat(e.target.value) || 0
                          }
                        }))}
                      />
                    </div>
                    <div className="space-y-2">
                      <Label htmlFor="animal-protection">动保板块</Label>
                      <Input
                        id="animal-protection"
                        type="number"
                        step="0.01"
                        placeholder="请输入增速（%）"
                        value={taskForm.strategic_growth_rates.animal_protection}
                        onChange={(e) => setTaskForm(prev => ({
                          ...prev,
                          strategic_growth_rates: {
                            ...prev.strategic_growth_rates,
                            animal_protection: parseFloat(e.target.value) || 0
                          }
                        }))}
                      />
                    </div>
                  </div>
                </div>
              )}

              {/* Description */}
              <div className="space-y-2">
                <Label htmlFor="description">任务描述（可选）</Label>
                <Textarea
                  id="description"
                  placeholder="输入任务描述..."
                  value={taskForm.description}
                  onChange={(e) => setTaskForm(prev => ({ ...prev, description: e.target.value }))}
                />
              </div>

              {/* Actions */}
              <div className="flex justify-end space-x-3">
                <Button variant="outline" onClick={() => {
                  setTaskForm({
                    task_name: '',
                    task_type: 'group_prediction',
                    company_ids: [],
                    product_ids: [],
                    prediction_years: '2025',
                    description: '',
                    strategic_growth_rates: {
                      human_drug_formulation: 0,
                      human_drug_raw_material: 0,
                      plant_protection: 0,
                      animal_protection: 0
                    }
                  })
                }}>
                  重置
                </Button>
                <Button onClick={() => setShowDemoAlert(true)} disabled={creating}>
                  {creating ? (
                    <>
                      <Clock className="h-4 w-4 mr-2 animate-spin" />
                      创建中...
                    </>
                  ) : (
                    <>
                      <Play className="h-4 w-4 mr-2" />
                      创建任务
                    </>
                  )}
                </Button>
              </div>
            </CardContent>
          </Card>
        </TabsContent>

        {/* Tasks Tab */}
        <TabsContent value="tasks">
          <Card>
            <CardHeader>
              <CardTitle>任务管理</CardTitle>
              <CardDescription>
                查看和管理所有预测任务
              </CardDescription>
            </CardHeader>
            <CardContent>
              {loading ? (
                <div className="text-center py-8 text-gray-500">
                  加载中...
                </div>
              ) : (
                <div className="space-y-4">
                  {tasks.map((task) => (
                    <div key={task.task_id} className="p-4 border rounded-lg">
                      <div className="flex items-center justify-between mb-3">
                        <div className="flex items-center space-x-3">
                          {getStatusIcon(task.status)}
                          <div>
                            <h3 className="font-medium text-gray-900">{task.task_name}</h3>
                            <p className="text-sm text-gray-500">
                              创建时间: {formatDate(task.created_at)}
                            </p>
                          </div>
                        </div>
                        <div className="flex items-center space-x-3">
                          {getStatusBadge(task.status)}
                        </div>
                      </div>
                      
                      {task.status === 'running' && (
                        <div className="space-y-2">
                          <div className="flex items-center justify-between">
                            <span className="text-sm font-medium">执行进度</span>
                            <span className="text-sm text-gray-500">{task.progress || 0}%</span>
                          </div>
                          <Progress value={task.progress || 0} className="w-full" />
                        </div>
                      )}
                    </div>
                  ))}
                  {tasks.length === 0 && (
                    <div className="text-center py-8 text-gray-500">
                      暂无任务
                    </div>
                  )}
                </div>
              )}
            </CardContent>
          </Card>
        </TabsContent>

        {/* Results Tab */}
        <TabsContent value="results">
          <Card>
            <CardHeader>
              <CardTitle>预测结果</CardTitle>
              <CardDescription>
                查看已完成任务的预测结果和AI分析
              </CardDescription>
            </CardHeader>
            <CardContent>
              <div className="space-y-4">
                {tasks.filter(task => task.status === 'completed').map((task) => (
                  <div key={task.task_id} className="p-4 border rounded-lg">
                    <div className="flex items-center justify-between">
                      <div className="flex items-center space-x-3">
                        <Brain className="h-8 w-8 text-purple-500" />
                        <div>
                          <h3 className="font-medium text-gray-900">{task.task_name}</h3>
                          <p className="text-sm text-gray-500">
                            完成时间: {formatDate(task.updated_at || task.created_at)}
                          </p>
                        </div>
                      </div>
                      <div className="flex items-center space-x-3">
                        <Badge variant="secondary" className="bg-green-100 text-green-800">
                          已完成
                        </Badge>
                        <Button
                          variant="outline"
                          size="sm"
                          onClick={() => handleViewPrediction(task)}
                          className="text-blue-600 hover:text-blue-800"
                        >
                          <Eye className="h-4 w-4 mr-2" />
                          查看详情
                        </Button>
                      </div>
                    </div>
                  </div>
                ))}
                {tasks.filter(task => task.status === 'completed').length === 0 && (
                  <div className="text-center py-8 text-gray-500">
                    暂无完成的任务
                  </div>
                )}
              </div>
            </CardContent>
          </Card>
        </TabsContent>
      </Tabs>

      {/* 预测数据展示模态框 */}
      {showPredictionModal && selectedTask && predictionData && (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4">
          <div className="bg-white rounded-lg shadow-xl max-w-7xl w-full max-h-[90vh] overflow-hidden">
            {/* 模态框头部 */}
            <div className="flex items-center justify-between p-6 border-b">
              <div>
                <h2 className="text-2xl font-bold text-gray-900">{selectedTask.task_name}</h2>
                <p className="text-gray-600 mt-1">预测结果展示</p>
              </div>
              <div className="flex items-center space-x-3">
                <Button 
                  variant="outline" 
                  size="sm"
                  onClick={() => apiService.exportTaskToExcel(selectedTask.task_id)}
                >
                  <Download className="h-4 w-4 mr-2" />
                  导出Excel
                </Button>
                <Button 
                  variant="ghost" 
                  size="sm" 
                  onClick={() => setShowPredictionModal(false)}
                >
                  <X className="h-4 w-4" />
                </Button>
              </div>
            </div>

            {/* 模态框内容 */}
            <div className="p-6 overflow-auto max-h-[calc(90vh-120px)]">
              <PredictionDataTable 
                task={selectedTask} 
                data={predictionData} 
              />
            </div>
          </div>
        </div>
      )}
    </div>
  )
}

// 预测数据表格组件
function PredictionDataTable({ task, data }) {
  const { results = [] } = data || {}
  
  // 按年份和板块分组数据
  const groupedData = results.reduce((acc, result) => {
    const year = result.prediction_year
    const sector = result.company_name
    
    if (!acc[year]) {
      acc[year] = {}
    }
    if (!acc[year][sector]) {
      acc[year][sector] = result
    }
    
    return acc
  }, {})
  
  const years = Object.keys(groupedData).sort()
  const sectors = ['人药制剂板块', '人药原料板块', '植保板块', '动保板块', '集团合计']
  
  // 格式化数字显示
  const formatNumber = (num, decimals = 2) => {
    if (num === null || num === undefined) return '-'
    return Number(num).toLocaleString('zh-CN', {
      minimumFractionDigits: decimals,
      maximumFractionDigits: decimals
    })
  }
  
  // 计算增长率
  const calculateGrowthRate = (current, previous) => {
    if (!previous || previous === 0) return '-'
    return (((current - previous) / previous) * 100).toFixed(2) + '%'
  }
  
  return (
    <div className="space-y-6">


      {/* 主要预测数据表格 */}
      <div className="bg-white border rounded-lg overflow-hidden">
        <div className="bg-gray-50 px-6 py-3 border-b">
          <h3 className="text-lg font-semibold text-gray-900 flex items-center">
            <Table className="h-5 w-5 mr-2" />
            预测数据总览
          </h3>
        </div>
        
        <div className="overflow-x-auto">
          <table className="w-full">
            <thead className="bg-gray-50">
              <tr>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  业务板块
                </th>
                {years.map(year => (
                  <th key={year} className="px-6 py-3 text-center text-xs font-medium text-gray-500 uppercase tracking-wider">
                    {year}年
                  </th>
                ))}
              </tr>
            </thead>
            <tbody className="bg-white divide-y divide-gray-200">
              {sectors.map(sector => (
                <tr key={sector} className={sector === '集团合计' ? 'bg-blue-50 font-semibold' : ''}>
                  <td className="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">
                    {sector}
                  </td>
                  {years.map(year => {
                    const data = groupedData[year]?.[sector]
                    return (
                      <td key={year} className="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                        {data ? (
                          <div className="space-y-1">
                            <div className="font-medium">
                              收入: {formatNumber(data.predicted_sales_amount, 2)}亿
                            </div>
                            <div className="text-gray-600">
                              利润: {formatNumber(data.predicted_unit_profit, 2)}亿
                            </div>
                            {data.comprehensive_rate && (
                              <div className="text-xs text-blue-600 font-medium">
                                综合增长率: {(data.comprehensive_rate * 100).toFixed(2)}%
                              </div>
                            )}
                          </div>
                        ) : (
                          <span className="text-gray-400">-</span>
                        )}
                      </td>
                    )
                  })}
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>

      {/* 详细数据表格 */}
      <div className="bg-white border rounded-lg overflow-hidden">
        <div className="bg-gray-50 px-6 py-3 border-b">
          <h3 className="text-lg font-semibold text-gray-900">详细预测数据</h3>
        </div>
        
        <div className="overflow-x-auto">
          <table className="w-full">
            <thead className="bg-gray-50">
              <tr>
                <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">业务板块</th>
                <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">预测年份</th>
                <th className="px-4 py-3 text-right text-xs font-medium text-gray-500 uppercase">销售收入(亿元)</th>
                <th className="px-4 py-3 text-right text-xs font-medium text-gray-500 uppercase">净利润(亿元)</th>
                <th className="px-4 py-3 text-right text-xs font-medium text-gray-500 uppercase">净利润率(%)</th>
                <th className="px-4 py-3 text-right text-xs font-medium text-gray-500 uppercase">综合增长率(%)</th>
              </tr>
            </thead>
            <tbody className="bg-white divide-y divide-gray-200">
              {results.map((result, index) => (
                <tr key={index} className={result.company_name === '集团合计' ? 'bg-blue-50' : ''}>
                  <td className="px-4 py-4 whitespace-nowrap text-sm font-medium text-gray-900">
                    {result.company_name}
                  </td>
                  <td className="px-4 py-4 whitespace-nowrap text-sm text-gray-900">
                    {result.prediction_year}
                  </td>
                  <td className="px-4 py-4 whitespace-nowrap text-sm text-gray-900 text-right">
                    {formatNumber(result.predicted_sales_amount, 2)}
                  </td>
                  <td className="px-4 py-4 whitespace-nowrap text-sm text-gray-900 text-right">
                    {formatNumber(result.predicted_unit_profit, 2)}
                  </td>
                  <td className="px-4 py-4 whitespace-nowrap text-sm text-gray-900 text-right">
                    {result.predicted_sales_amount > 0 
                      ? ((result.predicted_unit_profit / result.predicted_sales_amount) * 100).toFixed(2)
                      : '-'
                    }
                  </td>
                  <td className="px-4 py-4 whitespace-nowrap text-sm text-gray-900 text-right">
                    {result.comprehensive_rate 
                      ? (result.comprehensive_rate * 100).toFixed(2)
                      : '-'
                    }
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  )
}

